package com.sansi.bleFloodlight.bluetooth;

import android.bluetooth.BluetoothSocket;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class ConnectedThread extends Thread {
    private BluetoothSocket socket;
    private InputStream inStream;
    private OutputStream outStream;
    private Handler handler;

    public ConnectedThread(BluetoothSocket socket, Handler handler) {
        this.handler = handler;
        this.socket = socket;
        try {
            //获得输入输出流
            inStream = socket.getInputStream();
            outStream = socket.getOutputStream();
        } catch (IOException e) {
            Log.e("app", "temp sockets not created", e);
        }
    }

    @Override
    public void run() {
        byte[] buff = new byte[1024];
        int len = 0;
        //读数据需不断监听，写不需要
        while (true) {
            try {
                len = inStream.read(buff);
                //把读取到的数据发送给UI进行显示
                Message msg = handler.obtainMessage(BluetoothChat.MESSAGE_READ,
                        len, -1, buff);
                msg.sendToTarget();
            } catch (IOException e) {
                Log.e("app", "disconnected", e);
                //connectionLost();   //失去连接
                start();    //重新启动服务器
                break;
            }
        }
    }


    public void write(byte[] buffer) {
        try {
            outStream.write(buffer);
            outStream.flush();

            // Share the sent message back to the UI Activity
            handler.obtainMessage(BluetoothChat.MESSAGE_WRITE, -1, -1, buffer)
                    .sendToTarget();
        } catch (IOException e) {
            Log.e("app", "Exception during write", e);
        }
    }

    public void cancel() {
        try {
            socket.close();
        } catch (IOException e) {
            Log.e("app", "close() of connect socket failed", e);
        }
    }
}
